<template>
  <div id="title"><h2>采购管理--采购列表</h2></div>
  <span id="button-add">
    <router-link :to="{ name: 'purchaseAdd' }">
      <a-button type="primary">添加<plus-circle-outlined /></a-button>
      <router-view></router-view>
    </router-link>
  </span>
  <a-table
    :columns="columns"
    :data-source="data"
    :pagination="pagination"
    bordered
  >
    <template #bodyCell="{ column, text, record }">
      <template
        v-if="
          [
            'indexNum',
            'commodity',
            'supplier',
            'purchaseNum',
            'purchaseTime',
          ].includes(column.dataIndex)
        "
      >
        <div>
          <a-input
            v-if="editableData[record.key]"
            v-model:value="editableData[record.key][column.dataIndex]"
            style="margin: -5px 0"
          />
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
      <template v-else-if="column.dataIndex === 'operation'">
        <div class="editable-row-operations">
          <span v-if="editableData[record.key]">
            <a-typography-link @click="save(record)">
              <a-button type="primary" size="small"
                >保存</a-button
              ></a-typography-link
            >
            <a-popconfirm title="Sure to cancel?" @confirm="cancel(record.key)">
              <a><a-button type="dashed" size="small" danger>取消</a-button></a>
            </a-popconfirm>
          </span>
          <span v-else>
            <a-button
              type="primary"
              size="small"
              id="button-edit"
              @click="updatePur(record), showModal()"
              >编辑</a-button
            >

            <a-button
              type="danger"
              size="small"
              @click="deleteOnePurchase(record)"
              >删除</a-button
            >
          </span>
        </div>
      </template>
    </template>
  </a-table>
  <a-modal v-model:visible="visible" title="修改采购信息" @ok="handleOk">
    <a-form
      :model="forUpdate"
      v-bind="layout"
      name="nest-messages"
      :validate-messages="validateMessages"
      @finish="onFinish"
      labelAlign="left"
    >
      <a-form-item :name="['commodityName']" label="商品名称">
        <a-input v-model:value="Update.commodityName" />
      </a-form-item>
      <a-form-item :name="['supplierName']" label="供应商">
        <a-input v-model:value="Update.supplierName" />
      </a-form-item>
      <a-form-item :name="['Update', 'purchaseNum']" label="采购数量">
        <a-input v-model:value="Update.purchaseNum" />
      </a-form-item>

      <a-form-item :name="['Update', 'purchaseTime']" label="采购时间">
        <a-input v-model:value="Update.purchaseTime" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script>
import { cloneDeep } from "lodash-es";
import { defineComponent, reactive, ref } from "vue";
import { message } from "ant-design-vue";
const columns = [
  {
    title: "序号",
    dataIndex: "key",
    width: "10%",
  },
  {
    title: "商品",
    dataIndex: "commodity",
    width: "20%",
  },
  {
    title: "供应商",
    dataIndex: "supplier",
    width: "20%",
  },
  {
    title: "采购数量",
    dataIndex: "purchaseNum",
    width: "10%",
  },
  {
    title: "采购时间",
    dataIndex: "purchaseTime",
    width: "20%",
  },
  {
    title: "操作",
    dataIndex: "operation",
  },
];

let data = [];
import {
  getAllPurchase,
  updateOnePurchase,
  deletePurchase,
  addPurchase,
} from "@/api/purchase";
export default defineComponent({
  name: "purchase",
  data() {
    return {
      data,
      Update: {
        purchaseId: "",
        commodityId: "",
        supplierName: "",
        purchaseNum: 0,
        purchaseTime: "",
      },

      pagination: {
        total: 50,
        defaultPageSize: 10,
        showTotal: (total) => `共 ${total} 条数据`,
        showSizeChanger: true,
        pageSizeOptions: ["3", "5", "7", "10"],
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize),
      },
    };
  },
  methods: {
    updatePur(val) {
      this.Update.purchaseId = val.purchaseId;
      this.Update.commodityName = val.commodity;
      this.Update.supplierName = val.supplier;
      this.Update.purchaseNum = val.purchaseNum;
      this.Update.purchaseTime = val.purchaseTime;
    },
    async handleOk(e) {
      await updateOnePurchase(this.Update).then((res) => {
        if (res.code == 200) {
          message.success("修改成功");
          this.data = [];
          this.getPurchase();
        } else {
          message.error("修改失败");
        }
      });
    },

    deletemessage(val) {
      if (val == 200) {
        message.success("删除成功", 3);
      } else {
        message.error("删除失败", 3);
      }
    },
    async deleteOnePurchase(val) {
      await deletePurchase({ purchaseId: val.purchaseId }).then((res) => {
        if (res.code == 200) {
          console.log("删除成功");
          this.deletemessage(res.code);
          this.getPurchase();
        } else {
          this.deletemessage(res.code);
        }
      });
    },
    async getPurchase() {
      const res = await getAllPurchase({}).then((response) => {
        // console.log(i);
        this.data = [];
        let res = response.data;
        this.pagination.total = res.length;
        for (let i = 0; i < res.length; i++) {
          this.data.push({
            key: (i + 1).toString(),
            commodity: res[i].commodity.commodityName,
            supplier: res[i].supplier.supplierName,
            purchaseNum: res[i].purchaseNum,
            purchaseTime: res[i].purchaseTime,
            purchaseId: res[i].purchaseId,
            operation: "",
          });
        }
      });
    },
  },
  mounted() {
    this.getPurchase();
  },

  setup() {
    const layout = {
      labelCol: {
        span: 8,
      },
      wrapperCol: {
        span: 16,
      },
    };
    const validateMessages = {
      required: "${label} is required!",
    };
    const forUpdate = reactive({
      Update: {
        purchaseId: "",
        commodityId: "",
        supplierName: "",
        purchaseNum: 0,
        purchaseTime: "",
      },
    });
    const formState = reactive({
      purchase: {
        commodityName: "",
        supplierName: "",
        purchaseNum: "",
        purchaseTime: "",
      },
    });

    const onFinish = (values) => {
      console.log("Success:", values);
    };
    const visible = ref(false);
    const dataSource = ref(data);
    const editableData = reactive({});

    const edit = (key) => {
      editableData[key] = cloneDeep(
        dataSource.value.filter((item) => key === item.key)[0]
      );
    };

    const save = (val) => {
      console.log(typeof JSON.stringify(val));
      console.log(JSON.stringify(val));
      Object.assign(
        dataSource.value.filter((item) => val.key === item.key)[0],
        editableData[val.key]
      );
      delete editableData[val.key];
      UpdateList(val); //更新数据
    };

    const UpdateList = (val) => {
      updateOnePurchase(val).then((res) => {
        if (res.code == 200) {
          console.log("修改成功");
        }
      });
    };

    const cancel = (key) => {
      delete editableData[key];
    };

    visible.value = false;
    const showModal = () => {
      visible.value = true;
    };

    return {
      dataSource,
      columns,
      editingKey: "",
      editableData,
      edit,
      save,
      cancel,
      visible,
      showModal,
      formState,
      onFinish,
      layout,
      validateMessages,
      forUpdate,
      // AddOnePurchase,
    };
  },
});
</script>
<style scoped>
.editable-row-operations a {
  margin-right: 8px;
}
#button-edit {
  margin-right: 15px;
}
#button-add {
  float: left;
  display: block;
  margin-bottom: 10px;
}
#title {
  margin-left: 0px;
}
h2 {
  width: 190px;
  padding-left: 0px;
}
</style>